<template>
  <div :class="s.root">
    <ElInput
      v-model="newSource"
      :class="s.nameInput"
      placeholder="请输入宝宝姓名"
    />
    注：输入文字10字以内
    <div :class="s.hr"></div>
    <div :class="s.operations">
      <ElButton type="primary" round size="small" @click="add">确定</ElButton>
    </div>
    客户来源：
    <ElTable :data="sourceList" style="width: 100%" height="200">
      <ElTableColumn prop="source_name" label="类型"> </ElTableColumn>
      <ElTableColumn prop="id" label="操作" width="150">
        <template slot-scope="scope">
          <ElButton
            round
            plain
            size="small"
            type="primary"
            @click="remove(scope.row.id)"
            >删除</ElButton
          >
        </template>
      </ElTableColumn>
    </ElTable>
  </div>
</template>

<script>
import {http, catchAppError} from '@/util';
import url from '@/config';

export default {
  data() {
    return {
      newSource: '',
      sourceList: []
    };
  },
  beforeMount() {
    this.fetch();
  },
  methods: {
    fetch() {
      return http
        .get(url.getSource)
        .then(res => {
          this.sourceList = res;
        })
        .catch(catchAppError);
    },
    add() {
      if (this.newSource !== '') {
        const sourceFilter = this.sourceList.filter(
          item => item.source_name === this.newSource
        );
        if (sourceFilter.length === 0) {
          http
            .post(url.addSource, {source_name: this.newSource})
            .then(() => {
              this.fetch();
              this.newSource = '';
              this.$message.success('添加成功！');
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        } else {
          this.$message.error('来源已存在，请直接选择');
        }
      } else {
        this.$message.error('参数source_name不可以为空');
      }
    },
    remove(id) {
      http
        .post(url.deleteSource, {id})
        .then(() => {
          this.fetch();
          this.$message.success('删除成功！');
        })
        .catch(catchAppError);
    }
  }
};
</script>

<style lang="scss" module="s">
.root {
  .name-input {
    width: 230px;
  }
  .hr {
    height: 1px;
    border-bottom: 1px dashed #eee;
    margin-top: 15px;
    margin-bottom: 15px;
  }
  .operations {
    text-align: right;
  }
  :global(.el-table) {
    border: 1px solid #eee;
    margin-top: 10px;
  }
}
</style>

<style lang="scss">
.el-message--success {
  background-color: #c2daff;
  border-color: #c2daff;
}
.el-message .el-icon-success,
.el-message--success .el-message__content {
  color: #4b90ff;
}
</style>
